package com.sykj.fileupload.util;

import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class BaseTools {


	private static String uploadUrl = "/home/uploaded_files/";



	/**
	 * Jsoup转换工具
	 * @param url
	 * @return
	 */
	public static String documentBody (String url) {
		Element doc = Jsoup.parseBodyFragment(url).body();
		Elements pngs = doc.select("img[src]");
		String httpHost = "/files/";
		String path = "";
		for (Element element : pngs) {
			String imgUrl = element.attr("src");
			url = url.replace(imgUrl,httpHost+imgUrl);
		}
		return url;
	}
	/**
	 * Jsoup转换工具2
	 * 针对word
	 * @param url
	 * @return
	 */
	public static String documentBody2 (String url) {
		Element doc = Jsoup.parseBodyFragment(url).body();
		Elements pngs = doc.select("img[src]");
		String httpHost = "/files/";
		String path = "";
		for (Element element : pngs) {
			String imgUrl = element.attr("src");
			url = url.replace(imgUrl,httpHost+imgUrl);
			File file = new File(uploadUrl + imgUrl);
			File file2 = new File(uploadUrl + UUID.randomUUID() + "." + imgUrl.substring(imgUrl.lastIndexOf(".") + 1));
			try {
				copyFile(file,file2);
			} catch (IOException e) {
				e.printStackTrace();
			}
			path = "/files/"+ file2.getPath().substring(file2.getPath().lastIndexOf("\\") + 1,file2.getPath().length());
			url = url.replace(httpHost+imgUrl,path);

		}
		return url;
	}

	/**
	 * 复制文件
	 * @param fromFile
	 * @param toFile
	 * <br/>
	 * 2016年12月19日  下午3:31:50
	 * @throws IOException
	 */
	public static void copyFile(File fromFile,File toFile) throws IOException {
		FileInputStream ins = new FileInputStream(fromFile);
		FileOutputStream out = new FileOutputStream(toFile);
		byte[] b = new byte[1024];
		int n=0;
		while((n=ins.read(b))!=-1){
			out.write(b, 0, n);
		}

		ins.close();
		out.close();
	}
}
